<template>
	<view class="container" :style="{'--bg': common.appStyle.home_nav_color}">
		<!-- 导航条 -->
		<view class="cu-custom" :style="{ height: $wanlshop.wanlsys().height + 'px'}">
			<!-- <view class="cu-bar fixed bg-bgcolor" :style="{
					height: $wanlshop.wanlsys().height + 'px',
					paddingTop: $wanlshop.wanlsys().top + 'px',
					backgroundColor: common.appStyle.cart_nav_color ? common.appStyle.cart_nav_color : '#f7f7f7',
					backgroundImage: 'url(' + $wanlshop.oss( common.appStyle.cart_nav_image, 0, 50, 1, 'transparent', 'png' ) + ')',
					color: common.appStyle.cart_font_color == 'light' ? '#ffffff' : '#333333'
				}"> -->
			<view class="cu-bar fixed" :style="{
					height: $wanlshop.wanlsys().height + 'px',
					paddingTop: $wanlshop.wanlsys().top + 'px',
					backgroundColor: common.appStyle.home_nav_color,
					color: '#333333'
				}">
				<view class="action" @tap="operate()">
					<text v-if="cart.operate">完成</text>
					<text v-else>管理</text>
				</view>
				<view class="content" :style="{ top: $wanlshop.wanlsys().top + 'px' }">
					购物车
					<text class="text-sm">（共{{ cart.cartnum }}件宝贝）</text>
				</view>
			</view>
		</view>

		<!-- 购物车轮播图 -->
		<swiper class="swiper-cart" :circular="true" :indicator-dots="false" :autoplay="true" :interval="3000"
			:duration="1000">
			<swiper-item v-for="(item,index) in img " :key="index">
				<view class="swiper-item" @click="toActivity(item)">
					<image :src="$wanlshop.oss($wanlshop.oss(item.img_url))" mode="widthFix"></image>
				</view>
			</swiper-item>
		</swiper>

		<!-- 加购轮播图 -->
		<!-- <buy-more-swiper :price="cart.allsum" v-if="cart.list.length > 0" /> -->

		<block v-if="cart.list.length > 0">
			<view class="wanl-cart-shop radius-bock margin-bj padding-bj" v-for="(item, index) in cart.list"
				:key="index">

				<view class="wanl-cart-goods" v-for="(goods, keys) in item.products" :key="keys">
					<!-- 商品选择 -->
					<view class="text-xxl margin-right-sm" @tap="choose({ index: index, keys: keys })">
						<text v-if="goods.checked" class="wlIcon-xuanze-danxuan" :style="{color: '#FE8C00'}"></text>
						<text v-else class="wlIcon-xuanze wanl-gray-light"></text>
					</view>
					<view class="picture" @tap="onGoods(goods.goods_id)">
						<image :src="$wanlshop.oss(goods.image, 100, 100, 1)" mode="aspectFill"></image>
					</view>
					<view class="content">
						<view class="text-cut-2" style="font-size: 28rpx;" @tap="onGoods(goods.goods_id)">
							{{ goods.title }}
						</view>
						<view class="cu-tag wanl-gray opt" @tap="showModal(goods, keys)">
							规格：{{ goods.sku.difference.join(' ') }}<text class="wlIcon-fanhui2 margin-left-xs"></text>
						</view>
						<view class="flex justify-between align-center">
							<view class="text-price wanl-red">
								{{ goods.sku.price }}
							</view>
							<view class="wanl-numberBox solid">
								<view @tap="bcsub(goods)">
									<text class="wlIcon-jian round text-gray"
										:style="{background: common.appStyle.home_nav_color}"></text>
								</view>
								<view>{{ goods.number }}</view>
								<view @tap="bcadd(goods)">
									<text class="wlIcon-tianjia round"
										:style="{background: common.appStyle.home_nav_color}"></text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</block>
		<block class="margin-bj padding-bj" v-else>
			<wanl-empty src="cart_default3x" text="哎呀，购物车空空如也！" />
		</block>

		<view class="wanl-you-like margin-bottom-sm"
			:style="{ backgroundImage: 'url(' + $wanlshop.oss(common.appStyle.guess_you_like_icon) + ')' }"></view>
		<wanl-product :dataList="likeData" />
		<uni-load-more :status="status" :content-text="contentText" />

		<!-- #ifdef APP-PLUS -->
		<view style="height: 100rpx;"></view>
		<!-- #endif -->
		<view class="safeAreaBottom"></view>
		<!-- 操作栏 -->
		<view class="wanl-cart-foot fixedView solid-top edit" v-if="cart.operate">
			<view class="flex align-center" @tap="toCartchoose()">
				<view class="text-xxl">
					<text v-if="cart.status" class="wlIcon-xuanze-danxuan" :style="{color: '#FE8C00'}"></text>
					<text v-else class="wlIcon-xuanze wanl-gray-light"></text>
				</view>
				<view class="margin-left-sm">
					<text>{{ cart.status ? '取消' : '全选' }}</text>
				</view>
			</view>
			<view class="flex">
				<button class="cu-btn round line-red quick-cleaning" @tap="toEmpty()">快速清理</button>
				<button v-if="cart.allnum == 0" class="cu-btn round line-gray" style="height: 64rpx !important; width: 200rpx;">删除</button>
				<button v-else class="cu-btn round delete-btn" @tap="del()">删除</button>
			</view>
		</view>
		<view class="wanl-cart-foot fixedView solid-top account" v-else>
			<view class="flex align-center" @tap="toCartchoose()" v-if="cart.allnum == 0">
				<view class="text-xxl">
					<text class="wlIcon-xuanze wanl-gray-light"></text>
				</view>
				<view class="margin-left-sm">
					<text>全选</text>
				</view>
			</view>

			<view class="flex align-center" style="gap: 16rpx;" v-else @tap="toCartchoose()">
				<view class="text-xxl">
					<text v-if="cart.status" class="wlIcon-xuanze-danxuan" :style="{color: '#FE8C00'}"></text>
					<text v-else class="wlIcon-xuanze wanl-gray-light"></text>
				</view>
				<text>已选 {{ cart.allnum }}</text>
				<view>
					合计：
					<text class="text-price wanl-red">{{ cart.allsum }}</text>
				</view>
			</view>

			<view class="flex">
				<button v-if="cart.allnum == 0" class="cu-btn round"
					:style="{backgroundColor: '#FE8C00',color: 'white', opacity: 0.3}">去结算</button>
				<button v-else class="cu-btn round" :style="{backgroundColor: '#FE8C00',color: 'white'}" @tap="settlement()">
					去结算
				</button>
			</view>
		</view>

		<!-- 弹窗 -->
		<view class="WANL-MODAL text-sm" @touchmove.stop.prevent="moveHandle">
			<!-- 规格 -->
			<view class="cu-modal bottom-modal" :class="modalName == 'option' ? 'show' : ''" @tap="hideModal">
				<view class="cu-dialog fixedView" @tap.stop="" style="transform: translateX(-50%);">
					<view class="option wanl-modal">
						<view class="head text-left padding-bj align-start" style="gap: 20rpx;">
							<view class="cu-avatar radius-bock" style="flex-shrink: 0;"
								:style="{ backgroundImage: 'url(' + $wanlshop.oss(selectshop.thumbnail || goodsData.image, 100, 100) + ')' }">
							</view>

							<view>
								<view class="text-xl margin-bottom-sm" style="padding-right: 30rpx;">
									{{ goodsData.title }}
								</view>

								<view class="text-price wanl-red text-xl margin-bottom-xs">
									{{ selectshop.price || goodsData.interval_price }}
								</view>
								<view v-if="selectArr.join('')" class="wanl-gray margin-bottom-xs">
									库存 <text class="margin-lr-xs">{{ selectshop.stock || 0 }}</text> 件
								</view>

								<view class="text-sm margin-bottom-sm">
									<view v-if="selectArr.join('')">已选择：{{ selectArr.join(' ') }}</view>
									<view v-else>
										请选择：
										<text class="wanl-gray-light" v-for="(item, index) in goodsData.spu"
											:key="item.id">
											<block v-if="index != 0">-</block>
											{{ item.name }}
										</text>
									</view>
								</view>
							</view>

							<view class="close wlIcon-31guanbi" @tap="hideModal"></view>
						</view>

						<!-- 1.0.8升级 -->
						<scroll-view scroll-y="true" :style="{ maxHeight: wanlsys.screenHeight / 2 + 'px' }">
							<view class="opt text-left padding-bj solid-bottom" v-for="(value, spukey) in goodsData.spu"
								:key="value.id">
								<view class="text-df">{{ value.name }}</view>
								<view class="tag">
									<view class="cu-tag text-sm" v-for="(item, index) in value.item" :key="index"
										:class="[item.ishow ? '' : 'noactive', subIndex[spukey] == index ? 'active' : '']"
										@tap="skuClick(item, spukey, $event, index)">
										{{ item.name }}
									</view>
								</view>
							</view>
						</scroll-view>


						<view class="foot padding-lr-bj">
							<button class="cu-btn round text-bold text-white complete"
								:style="{backgroundColor: '#FE8C00'}" @tap="completeSelection">完成</button>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from 'vuex';
	export default {
		data() {
			return {
				reload: true,
				likeData: [],
				cartList: [],
				current_page: 1, //当前页码
				last_page: 1, //总页码
				img: [],
				status: 'loading',
				contentText: {
					contentdown: ' ',
					contentrefresh: '正在加载...',
					contentnomore: '没有更多数据了'
				},
				// 显示弹窗
				modalName: false,
				// 商品规格组合
				shopItemInfo: {}, //存放要和选中的值进行匹配的数据
				selectArr: [], //存放被选中的值
				subIndex: [], //是否选中 因为不确定是多规格还是但规格，所以这里定义数组来判断
				selectshop: {}, //存放最后选中的商品
				selectNum: 1, //选中数量
				//产品数据
				goodsData: {
					description: '·35%高易消化蛋白 ·0诱食剂 ·65%深海鱼肉添加', // 描述
					service_id: null, // 服务
					id: 0,
					category_id: 0,
					shop_id: 0,
					brand_id: 0,
					freight_id: 0,
					title: '',
					image: '',
					images: [],
					flag: '',
					content: '',
					category_attribute: [],
					activity_type: 'goods',
					price: null,
					interval_price: null,
					market_price: null,
					sales: 0,
					brand: {},
					freight: {
						name: '',
						isdelivery: 1
					},
					payment: 0,
					comment: 0,
					praise: 0,
					moderate: 0,
					negative: 0,
					like: 0,
					views: 0,
					status: '',
					category: {},
					follow: true,
					sku: [],
					spu: [],
					promotion: [],
					coupon: [],
					comment_list: {
						data: [],
						figure: 0,
						tag: []
					},
					shop: {
						find_user: {
							fans: 0
						},
						city: ''
					},
					shop_recommend: {}
				},
				goods_keys: 0,  // 修改规格索引
				old_sku_id: '', // 原来的sku_id
				selectGoods: {}, // 原来规格商品
				cartShareImage: '',  // 购物车分享图片
				cartShareDesc: '',   // 购物车分享文案
			};
		},
		onReachBottom() {
			//判断是否最后一页
			if (this.current_page >= this.last_page) {
				this.status = 'noMore';
			} else {
				this.reload = false;
				this.current_page = this.current_page + 1; //页码+1
				this.status = 'loading';
				this.loadlikeData();
			}
		},
		computed: {
			...mapState(['cart', 'common']),
			canCount() {
				return this.subIndex.some(item => item === -1);
			},
		},
		watch: {
			'cart.list'(n, o) {
				console.log('n', n)
			}
		},
		onShow() {
			// 修改导航栏颜色
			uni.setNavigationBarColor({
				frontColor: '#000000',
				backgroundColor: '#ffffff'
			});
		},
		onLoad() {
			this.wanlsys = this.$wanlshop.wanlsys();
			// 加载猜你喜欢
			this.loadlikeData();
			this.loadData()
		},
		methods: {
			...mapActions({
				operate: 'cart/operate', // 管理购物车
				choose: 'cart/choose', // 选择商品
				shopchoose: 'cart/shopchoose', // 选择店铺
				changesku: 'cart/changesku', // 修改规格
				bcadd: 'cart/bcadd', // 添加数量
				bcsub: 'cart/bcsub', // 减少数量
				move: 'cart/move', // 移动购物车
				settlement: 'cart/settlement', // 结算购物车
				del: 'cart/del' // 删除选中购物车
			}),
			async loadData() {
				this.$api.post({
					url: `/wanlshop/product/hotsale?page=${1}`,
					success: res => {
						res.data.forEach((e, i) => {
							if (e.column == "轮播图") {
								this.img = [...this.img, e]
							}
							if(e.row == "购物车分享") {
								this.cartShareImage = e.img_url;
								this.cartShareDesc = e.desc;
							}
						})
					}
				})
			},
			async loadlikeData() {
				this.$api.get({
					url: '/wanlshop/product/likes?pages=cart',
					data: {
						page: this.current_page
					},
					success: res => {
						this.likeData = this.reload ? res.data : this.likeData.concat(res.data); //评论数据 追加
						this.current_page = res.current_page; //当前页码
						this.last_page = res.last_page; //总页码
						this.status = 'more';
					}
				});
			},
			// 跳转活动页面
			toActivity(item) {
				this.$api.post({
					loadingTip: '加载中',
					url: `/wanlshop/activity/detail`,
					data: {
						type: 'cart',
						//type_id: item.id
					},
					success: result => {
						uni.navigateTo({
							url: `/pages/page/activityPage?type=cart`,
							success: (res) => {
								res.eventChannel.emit('data', {
									activity: result?.title,
									productList: result?.categories,
									headerImage: result?.header_img,
									footerImage: result?.footer_img,
									cartShareImage: this.cartShareImage,
									cartShareDesc: this.cartShareDesc,
								})
							}
						})
					}
				})
			},
			// 禁止空购物车点击全选
			toCartchoose() {
				if (this.$store.state.cart.list.length == 0) {
					uni.showModal({
						content: '购物车没有任何宝贝，马上去选一个心仪的宝贝吧~',
						success: res => {
							if (res.confirm) {
								this.$wanlshop.on('/pages/category');
							}
						}
					});
				} else {
					this.$store.dispatch('cart/cartchoose');
				}
			},
			toEmpty() {
				uni.showModal({
					content: '确定清空购物车？',
					success: res => {
						if (res.confirm) {
							this.$store.dispatch('cart/empty');
						}
					}
				});
			},

			//禁止父元素滑动
			moveHandle() {},

			async loadGoods(option) {
				//加载商品
				this.$api.get({
					loadingTip: '加载中',
					url: '/wanlshop/product/goods',
					data: option,
					success: res => {
						// 价格区间
						if (res.sku.length == 0) {
							res.interval_price = res.price;
							res.market_price = res.price;
						} else {
							let price = [],
								market_price = [];
							for (let value of res.sku) {
								price.push(value.price);
								market_price.push(value.market_price);
							}
							let minPrice = Math.min.apply(null, price),
								maxPrice = Math.max.apply(null, price),
								maxMarketPrice = Math.max.apply(null, market_price);
							res.interval_price = minPrice == maxPrice ? Number(minPrice).toFixed(2) : (
								minPrice + '-' + Number(maxPrice).toFixed(2)); //区间价格
							res.market_price = Number(maxMarketPrice).toFixed(2); //最大市场价
						}

						this.goodsData = res;
						console.log('商品详细信息', this.goodsData)

						// 商品规格组合
						this.goodsData.spu.map(item => {
							this.selectArr.push('');
							this.subIndex.push(-1);
						});
						this.checkItem(); //计算sku里面规格形成路径
						this.checkInpath(-1); //传-1是为了不跳过循环

						// 打开弹窗
						this.modalName = 'option';
						console.log('selectarr', this.selectArr)
					}
				});
			},
			// 商品规格组合 选择
			skuClick(value, spukey, event, index) {
				if (value.ishow) {
					if (this.selectArr[spukey] != value.name) {
						this.$set(this.selectArr, spukey, value.name);
						this.$set(this.subIndex, spukey, index);
					} else {
						this.$set(this.selectArr, spukey, '');
						this.$set(this.subIndex, spukey, -1);
					}
					this.checkInpath(spukey);
					//如果全部选完
					if (this.selectArr.every(item => item != '')) {
						this.selectshop = this.shopItemInfo[this.selectArr];
						this.selectNum = 1;
					}
				}
			},
			//循环所有属性判断哪些属性可选
			checkInpath(clickIndex) {

				//当前选中的兄弟节点和已选中属性不需要循环
				for (let i = 0, len = this.goodsData.spu.length; i < len; i++) {
					if (i == clickIndex) {
						continue;
					}
					let len2 = this.goodsData.spu[i].item.length;
					for (let j = 0; j < len2; j++) {
						if (this.subIndex[i] != -1 && j == this.subIndex[i]) {
							continue;
						}
						let choosed_copy = [...this.selectArr];
						this.$set(choosed_copy, i, this.goodsData.spu[i].item[j].name);
						let choosed_copy2 = choosed_copy.filter(item => item !== '' && typeof item !== 'undefined');
						if (this.shopItemInfo.hasOwnProperty(choosed_copy2)) {
							this.$set(this.goodsData.spu[i].item[j], 'ishow', true);
						} else {
							this.$set(this.goodsData.spu[i].item[j], 'ishow', false);
						}
					}
				}
				// console.log(this.goodsData.spu)
			},
			//计算有多小种可选路径
			checkItem() {
				let result = this.goodsData.sku.reduce(
					(arrs, items) => {
						return arrs.concat(
							items.difference.reduce(
								(arr, item) => {
									return arr.concat(
										arr.map(item2 => {
											//利用对象属性的唯一性实现二维数组去重
											if (!this.shopItemInfo.hasOwnProperty([...item2, item])) {
												this.shopItemInfo[[...item2, item]] = items;
											}
											return [...item2, item];
										})
									);
								},
								[
									[]
								]
							)
						);
					},
					[
						[]
					]
				);
			},
			// 完成修改
			completeSelection() {
				//console.log('完成', this.selectArr.length)
				console.log("ddddddddddddddddd", this.goodsData);
				if (this.selectArr[0] != '') {
					this.$store.dispatch('cart/changesku', {
						shop_id: this.goodsData.shop_id,
						shop_name: this.goodsData.shop.shopname,
						goods_id: this.goodsData.id,
						title: this.goodsData.title,
						//number: this.selectNum,
						number: this.selectGoods.number,
						image: this.goodsData.image,
						sku: this.selectshop,
						sku_id: this.selectshop.id,
						//sum: this.$wanlshop.bcmul(this.selectshop.price, this.selectNum),
						sum: this.$wanlshop.bcmul(this.selectshop.price, this.selectGoods.number),
						store_id: this.goodsData.service?.id || undefined,
						store_service_id: this.goodsData.store_service_id || undefined,
						goods_keys: this.goods_keys,
						old_sku_id: this.old_sku_id,
					});
					this.hideModal();
				} else {
					this.$wanlshop.msg('请选择规格')
				}
			},

			// 弹出层
			showModal(goods, keys) {
				console.log('cartgoods', goods, keys)
				console.log('shopItemInfo', this.shopItemInfo)
				console.log('selectArr', this.selectArr)
				console.log('subIndex', this.subIndex)
				console.log('selectshop', this.selectshop)
				this.goods_keys = keys;
				this.old_sku_id = goods.sku_id;
				this.selectGoods = goods;
				this.shopItemInfo = {};
				this.selectArr = [];
				this.subIndex = [];
				this.selectshop = {};
				this.loadGoods({
					id: goods.goods_id
				});
			},
			// 关闭弹出层
			hideModal() {
				this.modalName = false;
			},
		}
	};
</script>

<style>
	.container {
		background-color: var(--bg);
	}

	.wanl-gray-light {
		color: #eee;
	}

	.swiper-cart {
		margin: 26rpx;
		border-radius: 18rpx;
		overflow: hidden;
		box-shadow: 0px 0px 6px -3px rgba(0, 0, 0, 0.2);
	}

	.wanl-cart-shop {
		background-color: #ffffff;
		box-shadow: 0px 0px 6px -3px rgba(0, 0, 0, 0.2);
	}

	/* #ifndef MP-ALIPAY */
	.wanl-cart-shop radio::before,
	.wanl-cart-shop checkbox::before {
		margin-top: -7px;
		right: 1px;
	}

	.wanl-cart-shop radio .wx-radio-input,
	.wanl-cart-shop checkbox .wx-checkbox-input,
	.wanl-cart-shop radio .uni-radio-input,
	.wanl-cart-shop checkbox .uni-checkbox-input {
		margin: 0;
		width: 16px;
		height: 16px;
	}

	/* #endif */
	.wanl-cart-shop checkbox-group {
		margin-right: 25rpx;
	}

	.wanl-cart-shop .shop {
		position: relative;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.wanl-cart-shop .shop .shopname {
		position: absolute;
		display: flex;
		align-items: center;
		left: 60rpx;
	}

	.wanl-cart-shop .shop uni-checkbox .uni-checkbox-input {
		border: 1px solid #cccccc;
	}

	/* 商品 */
	.wanl-cart-goods {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.wanl-cart-goods:last-child {
		margin-bottom: 18rpx;
	}

	.wanl-cart-goods .picture {
		width: 180rpx;
		height: 180rpx;
	}

	.wanl-cart-goods .picture image {
		width: 180rpx;
		height: 180rpx;
		overflow: hidden;
		border-radius: 20rpx;
	}

	/* 1.0.6升级 */
	.wanl-cart-goods .content {
		padding-left: 25rpx;
		width: 100%;
		overflow: hidden;
	}

	.wanl-cart-goods .content .opt {
		font-size: 24rpx;
		padding: 0;
		color: #555555;
		height: 32rpx;
		background-color: transparent;
		font-weight: 300;
		margin-top: 10rpx;
		margin-bottom: 25rpx;
		border-radius: 4rpx;
	}

	.wanl-cart-goods .content .opt text {
		transform: rotateZ(90deg);
	}

	/* 操作条 */
	.wanl-cart-foot {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		z-index: 800;
		min-height: 52px;
		background-color: #ffffff;
		padding: 0 46rpx;
	}

	.wanl-cart-foot.solid:after {}

	/* #ifndef MP-ALIPAY */
	.wanl-cart-foot radio:before,
	.wanl-cart-foot checkbox:before {
		margin-top: -7px;
		right: 1px;
	}

	.wanl-cart-foot radio .wx-radio-input,
	.wanl-cart-foot checkbox .wx-checkbox-input,
	.wanl-cart-foot radio .uni-radio-input,
	.wanl-cart-foot checkbox .uni-checkbox-input {
		margin: 0;
		width: 16px;
		height: 16px;
	}

	/* #endif */
	.wanl-cart-foot.account button {
		margin-left: 25rpx;
	}

	.wanl-cart-foot.edit button {
		margin-left: 20rpx;
	}

	.wanl-cart-foot.account .cu-btn {
		padding: 0 60rpx;
		font-size: 28rpx;
		height: 72rpx;
		margin-top: 6rpx;
		/* border-radius: 20rpx; */
	}

	.wanl-cart-foot.edit .cu-btn {
		padding: 0 30rpx;
		font-size: 24rpx;
		height: 56rpx;
	}
	
	.quick-cleaning {
		color: #000000;
		width: 200rpx;
		height: 64rpx !important;
	}
	.quick-cleaning::after {
		border: 2rpx solid #b6b6b6 !important;
	}
	.delete-btn {
		height: 64rpx !important;
		background-color: #fd8c00 !important;
		width: 200rpx;
		color: #ffffff !important;
	}
</style>